﻿using Framework;
using Microsoft.Win32;
using System.Windows.Forms;

namespace Koala.JiraTool.AutoStart
{
    internal class MainFormEvent : IMainFormEvent
    {
        private readonly MainControl _mainControl;
        private readonly ITabController _tabController;
        private readonly IDataPersistence _dataPersistence;

        public MainFormEvent(MainControl mainControl, ITabController tabController, IDataPersistence dataPersistence)
        {
            _mainControl = mainControl;
            _tabController = tabController;
            _dataPersistence = dataPersistence;
        }

        #region Implementation of IMainFormEvent

        /// <summary>
        /// 主窗体加载完毕。
        /// </summary>
        public void LoadOk()
        {
            _tabController.OpenTab("自动启动", tabPage => tabPage.Controls.Add(_mainControl), false);
            RunWhenStart(true, "Koala.JiraTool", Application.ExecutablePath);
        }

        #endregion Implementation of IMainFormEvent

        #region Private Method

        /// <summary>
        /// 开机启动项
        /// </summary>
        /// <param name="started">是否启动</param>
        /// <param name="name">启动值的名称</param>
        /// <param name="path">启动程序的路径</param>
        public void RunWhenStart(bool started, string name, string path)
        {
            var settings = new Settings { IsAutoStart = started };
            var hklm = Registry.LocalMachine;
            try
            {
                var run = hklm.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                if (started)
                {
                    run.SetValue(name, path);
                    _dataPersistence.Save(settings);
                }
                else
                {
                    run.DeleteValue(name);
                    _dataPersistence.Save(settings);
                }
            }
            catch
            {
            }
            finally
            {
                hklm.Close();
            }
        }

        #endregion Private Method
    }
}